<template>
  <!--提交用户申请单-->
  <div  v-loading.fullscreen.lock="fullscreenLoading"></div>
  <basic-dialog v-model="dialog.showDialog" :title="dialog.title" width="1200"
                :autoClose="false" :hideFooter="true">
    <basic-crud  ref="crudRef" :option="options" :autoLoad="false"
                 v-model="formData"
                 :fastSearch="{}"
                 :before-open="beforeOpen"
                 @row-click="handleRowClick"
                 :row-save="handleAdd"
                 :row-update="handleEdit"
                 :row-del="handleDelete">
      <template #fileNames="{ row }">
        <el-button type="text" v-for="file in row.fileList" :key="file.id"  @click="downloadFileHandler(file)">{{
            `${file.showName}.${file.fileExtension};`
          }}</el-button>
      </template>
      <template #fileNames-form>
        <el-button type="text" v-for="file in formData.fileList" :key="file.id"  @click="downloadFileHandler(file)">{{
            `${file.showName}.${file.fileExtension};`
          }}</el-button>
      </template>
      <template #menu-right>
        <div style="display: flex;align-items: center;margin-right: 10px;">
          <span style="width: 10px;text-align: right"></span>
          <el-input v-model="fastSearchText" clearable :placeholder="'请输入单号回车查询'" size="small"
                    style="margin-right: 5px;width: 400px" @clear="fastSearchHandler"
                    @keyup.enter.native="fastSearchHandler">
            <template #suffix>
              <el-icon class="el-input__icon" style="cursor: pointer" @click="fastSearchHandler"><search /></el-icon>
            </template>
          </el-input>
        </div>
      </template>
      <template #menu-left>
        <avue-upload v-if="!onlyShow"  :showFileList="false" style="margin-left: 10px;"
                     :data="extraData"
                     :fileText="'文件上传'"
                     :action="uploadObject.action"
                     :headers="uploadObject.headers"
                     :propsHttp="uploadObject.propsHttp"
                     :upload-after="uploadAfter"
                     :upload-before="uploadBefore"
                     type="upload"
        ></avue-upload>
      </template>
    </basic-crud>
  </basic-dialog>
</template>

<script setup>
import {defineExpose, ref} from "vue";
import { formatDate,formatMilliseconds } from "@/utils/formatTime";
import {downloadFile} from "@/utils/file.js";
import { getWorkOrder } from "@/apis/mes/processTask";
import {useUserStore} from '@/store/user';
import {ElMessage} from "element-plus";
const {token,userInfo} = useUserStore();
import {
  apiGetList,
  postAdd,
  putEdit,
  deleteDel,
} from "@/apis/mes/mesSubmitCode.js";

const emits = defineEmits(['refresh-parent'])

const dialog = ref({
  showDialog: false,
  title: "提交用户申请单"
})
const uploadObject = ref({
  propsHttp: {
    res: "obj",
    name: "obj.name",
    url: "fileViewUrl",
  },
  headers: {
    'h-authorization-token': token
  },
  action: '/API/mes/fileController/uploadFile',
});

const parentRow = ref({});
const onlyShow = ref(false);
const doFirst = ref(false);
const searchData=ref({})

// 打开新增编辑对话框
const openDialog = (row, onlyShowValue) => {
  dialog.value.showDialog = true;
  parentRow.value=row;
  doFirst.value = false;
  onlyShow.value=onlyShowValue
  options.value.addBtn= !onlyShow.value
  options.value.editBtn= !onlyShow.value
  options.value.delBtn= !onlyShow.value
  options.value.menu= !onlyShow.value

  searchData.value={
    processTaskId:parentRow.value.id
  }
  getTableList()
};

const crudRef=ref(null);
const formData=ref({})
const options= ref({
  addBtn: false,
  editBtn: false,
  delBtn: false,
  refreshBtn: false,
  viewBtn:false,
  align: "center",
  height: "570px",
  menu: false,
  menuWidth: 120,
  cellBtn:true,
  column: [{
    prop:'name',
    label:'类型',
    type:'select',
    width:160,
    cell: true,
    dicData:[{
      value:'提交用户申请单',
      label:'提交用户申请单'
    },{
      value:'检验报告单',
      label: '检验报告单'
    }],
    rules:[{
      required:true,message:'类型不能为空',trigger:'blur'
    }]
  },{
    prop:'code',
    label:'单号',
    minWidth:260,
    cell: true,
    rules:[{
      required:true,message:'单号不能为空',trigger:'blur'
    }]
  },
    {
      label: "附件",
      prop: "fileNames",
      minWidth: 300,
      display: false,
    }]
})

const fullscreenLoading = ref(false)
const getTableList=()=> {
  fullscreenLoading.value = true
  apiGetList(searchData.value,fullscreenLoading).then((res) => {
    if (res.success) {
      if (!onlyShow.value && res.total == 0 && !doFirst.value) {
        crudRef.value.crudRef.rowAdd();
      }else {
        doFirst.value = true;
        crudRef.value.tableData = res.data;
        crudRef.value.pageData.total = res.total;
      }
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(() => {ElMessage.error("获取列表数据失败!")});
}

const fastSearchText=ref('')
//多属性快速查询
const fastSearchHandler=()=> {
  if(fastSearchText.value){
    searchData.value={
      processTaskId: parentRow.value.id,
      fastColumn:'code',
      fastText:fastSearchText.value
    }
  }else{
    searchData.value={
      processTaskId: parentRow.value.id
    }
  }
  getTableList();
}

const currentRow=ref(null);
const extraData=ref({})
const handleRowClick=(row) =>{
  currentRow.value=row
  extraData.value={
    ownId:row.id,
    ownBus:row.bus
  }
}

const uploadBefore=(file, done, loading)=> {
  if (!extraData.value.ownId) {
    ElMessage.error("请先点击行数据选中一条数据！");
    loading();
  } else {
    done();
  }
}
//上传后事件
const uploadAfter=(res, done, loading)=> {
  ElMessage.success("上传成功！");
  getTableList();
  loading();
  done();
  extraData.value={}
}

const beforeOpen=(done, type)=> {
  if (type == "add") {
    //先从后台获取下工单的信息，用于显示产品等几个属性
    getWorkOrder(parentRow.value.id).then((obj) => {
      if (
          !obj.pdmProductCode ||
          obj.pdmProductCode == null ||
          obj.pdmProductCode == ""
      ) {
        return ElMessage.error("任务的产品编号都还没有添加，请先执行开工");
      }
      formData.value.processTaskId = parentRow.value.id;
      formData.value.specificationTaskId = parentRow.value.specificationTaskId;
      done();
    });
  }else {
    done();
  }
}
// 新增
const handleAdd=(form, done, loading)=> {
  postAdd(form).then((res) => {
    ElMessage.success("新增数据成功!");
    refreshHandler();
  }).finally((res) => {
    loading()
    done(form);
  });
}
// 编辑
const handleEdit=(form, index, done, loading)=> {
  putEdit(form).then((res) => {
    ElMessage.success("修改数据成功!");
    getTableList();
    done(form);
  }).finally((res) => {
    loading()
    done(form);
  });
}

// 删除
const handleDelete=(row)=> {
  ElMessageBox.confirm(`此操作将永久删除数据, 是否继续?`, "提示").then(() => {
    deleteDel(row.id).then((res) => {
      ElMessage.success("删除成功");
      doFirst.value = true;
      refreshHandler();
    });
  }).catch(() => {
  });
}

//文件下载
const downloadFileHandler=async (row)=> {
  downloadFile(row.id, row.name, "/mes");
}
const refreshHandler=()=> {
  getTableList();
  emits('refresh-parent')
}

defineExpose({
  openDialog
})
</script>

<style scoped>

</style>